package com.zijin.aspect;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.zijin.annotation.Authority;
import com.zijin.service.user.IRoleService;
import com.zijin.config.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @Title: AuthorityJudgmentAspect
 * @Author JWei Xu
 * @Package com.zijin.aspect
 * @Date 2025/2/1 19:55
 * @description: 权限判断的切入点
 */

@Aspect
@Component
@Slf4j
public class AuthorityJudgmentAspect {

    @Resource
    @Lazy
    IRoleService roleService;

    @Pointcut("@annotation(com.zijin.annotation.Authority)")
    public void pt(){};

    @Before("pt()")
    public void autoFill(JoinPoint joinPoint){
        log.info("开始权限判断...");
        //获取到当前被拦截的方法上的数据库操作类型
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();//方法签名对象
        Authority authority = signature.getMethod().getAnnotation(Authority.class);//获得方法上的注解对象
        String[] value = authority.value();//获得数据库操作类型

        boolean all = authority.isAll();

        if(all){
            if (!SecurityUtils.hasAllRole(value)) {
                return;//结束这个方法
            }
        }

        if(ObjectUtil.isEmpty(all) || BooleanUtil.isFalse(all)) {
            if (!SecurityUtils.hasRole(value)) {
                return;//结束这个方法
            }

        }


    }
}
